package cn.tedu.mintmall.service.Impl;

import cn.tedu.mintmall.dto.SpuAddNewDTO;
import cn.tedu.mintmall.dto.SpuUpdateDTO;
import cn.tedu.mintmall.entity.Spu;
import cn.tedu.mintmall.exception.MintmallServiceException;
import cn.tedu.mintmall.mapper.CategoryMapper;
import cn.tedu.mintmall.mapper.SpuMapper;
import cn.tedu.mintmall.restful.ResponseCode;
import cn.tedu.mintmall.service.ISpuService;
import cn.tedu.mintmall.vo.CategoryDetailsVO;
import cn.tedu.mintmall.vo.SpuStandardVO;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class SpuServiceImpl implements ISpuService {

    @Autowired
    private SpuMapper spuMapper;
    @Autowired
    private CategoryMapper categoryMapper;

    @Override
    public void addNew(SpuAddNewDTO spuAddNewDTO) {
        Long categoryId = spuAddNewDTO.getCategoryId();
        CategoryDetailsVO categoryDetailsVO = categoryMapper.getDetailsById(categoryId);
        // 类别是否存在
        if(categoryDetailsVO == null){
            throw new MintmallServiceException(ResponseCode.NOT_FOUND,"选择的类别不存在");
        }
        // 类别是否禁用
        if(categoryDetailsVO.getEnable() == null || categoryDetailsVO.getEnable() == 0){
            throw new MintmallServiceException(ResponseCode.BAD_REQUEST,"选择的类别已禁用");
        }
        // 类别是否包含子级,不能在父级类别中创建spu
        if(categoryDetailsVO.getIsParent().equals(1)){
            throw new MintmallServiceException(ResponseCode.BAD_REQUEST,"选择的类别包含子级");
        }
        Spu spu = new Spu();
        BeanUtils.copyProperties(spuAddNewDTO,spu);
        spu.setCategoryName(categoryDetailsVO.getName());
        spu.setSales(0);
        spu.setCommentCount(0);
        spu.setPositiveCommentCount(0);
        spu.setSort(spuAddNewDTO.getSort());
        spu.setDeleted(0);
        spu.setNewArrival(0);
        spu.setRecommend(0);
        spu.setChecked(0);
        spu.setCheckUser(null);
        spu.setGmtCheck(null);
        spuMapper.insert(spu);
    }

    @Override
    public void deleteSpuById(Long id) {
        spuMapper.deleteById(id);
    }

    @Override
    public void updateSpuById(Long id, SpuUpdateDTO spuUpdateDTO) {
        Spu spu = new Spu();
        BeanUtils.copyProperties(spuUpdateDTO,spu);
        spuMapper.update(spu);
    }

    @Override
    public SpuStandardVO getSpuDetailById(Long id) {
        SpuStandardVO spuStandardVO = spuMapper.getById(id);
        if(spuStandardVO == null){
            throw new MintmallServiceException(ResponseCode.NOT_FOUND,"查询spu数据不存在");
        }
        return spuStandardVO;
    }
}
